# design date：2017/6/19
# designed by: husky
import sys,os
import datetime
import time
BASE_PATH = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))
)
sys.path.insert(0,BASE_PATH)

from bin import get_Webdriver


class Data_Retrieval:
    """网站暂未完成  """
    def __init__(self):
        self.driver = get_Webdriver.Get_Webdriver().driver

    def jumptoFilepage(self):
        """跳转到历史数据检索"""
        self.driver.click("link_text=>数据计算")
        self.driver.click("link_text=>历史数据检索")

    def getHelpMsg(self):
        """获得帮助 即鼠标悬浮在问号上的提示信息"""
        helpMsg=[]
        self.driver.get_attribute()
        helpMsg.append(self.dr.find_element_by_xpath(
            ".//*[@class='icon-question-sign popovers tooltips_size']"
        ).get_attribute("data-content"))
        eles=self.dr.find_elements_by_xpath(".//*[@class='icon-question-sign popovers pull-right tooltips_size']")
        for i in eles:
            helpMsg.append(i.get_attribute("data-content"))
        return helpMsg

    def getDefaultMsgInAccurate(self):
        """"获得精确检索的默认信息 即输入框中浅灰字体的默认信息"""
        try:self.dr.find_element_by_xpath(".//*[@id='query1']").click()
        except:pass
        defaultMsg=[]
        defaultMsg.append(self.dr.find_element_by_xpath(".//*[@id='w1']").get_attribute("placeholder"))
        defaultMsg.append(self.dr.find_element_by_xpath(".//*[@id='w2']").get_attribute("placeholder"))
        defaultMsg.append(self.dr.find_element_by_xpath(".//*[@id='w3']").get_attribute("placeholder"))
        return defaultMsg

    def getDefaultMsgInAdvanced(self):
        """"获得高级检索的默认信息 即输入框中浅灰字体的默认信息"""
        try:self.dr.find_element_by_xpath(".//*[@id='query2']").click()
        except:pass
        defaultMsg=[]
        defaultMsg.append(self.dr.find_element_by_xpath(".//*[@id='user_logic']").get_attribute("placeholder"))
        defaultMsg.append(self.dr.find_element_by_xpath(".//*[@id='amb_w_logic']").get_attribute("placeholder"))
        return defaultMsg

    def getDefaultMsgInAdvancedSetting(self):
        """"获得高级设置中的的默认信息 即输入框中浅灰字体的默认信息"""
        try:self.dr.find_element_by_xpath(".//*[@data-original-title='展开高级设置']/..").click()
        except:pass
        defaultMsg=[]
        defaultMsg.append(self.dr.find_element_by_xpath(".//*[@id='domain']").get_attribute("placeholder"))
        defaultMsg.append(self.dr.find_element_by_xpath(".//*[@id='channel']").get_attribute("placeholder"))
        defaultMsg.append(self.dr.find_element_by_xpath(".//*[@id='source']").get_attribute("placeholder"))
        return defaultMsg

    def clickShowMoreMediaType(self):
        """展示更多媒体类型"""
        self.dr.find_element_by_xpath(".//*[@data-original-title='查看更多媒体类型']").click()
        time.sleep(2)

    def clickShowDefaultMediaType(self):
        """收起更多媒体类型"""
        self.dr.find_element_by_xpath(".//*[@data-original-title='收起']").click()
        time.sleep(2)

    def chooseDomesticAndForeign(self,param="2"):
        """选择境内外数据
        "1"全部   "2" 境内  "3"境外    """
        param=param
        self.dr.find_element_by_xpath(".//*[@class='checkbox-inline paddingleft0']/../label[{}]".format(param)).click()

    def cancelChooseMediaType(self,mediaType=[]):
        """取消选择的媒体类型，支持中文 以元组或列表形式传输"""
        if len(mediaType)==0:
            return "并未传递需要取消选择的媒体类型"
        eles = self.dr.find_elements_by_xpath(ReadConfig().mediaTypes_box_xpath)
        for i in range (len(eles)):
            if eles[i].text in mediaType:
                eles[i].click()

    def chooseMediaType(self,mediaType=[]):
        """选择的媒体类型，支持中文 以元组或列表形式传输"""
        if mediaType == "点击反选":
            return self.dr.find_element_by_xpath(".//*[@id='reverse']").click()
        if mediaType == "点击全选":
            return self.dr.find_element_by_xpath(".//*[@id='selectAll']").click()
        if len(mediaType)==0:
            return "并未传递需要取消选择的媒体类型"
        self.dr.find_element_by_xpath(".//*[@id='reverse']").click()
        eles = self.dr.find_elements_by_xpath(ReadConfig().mediaTypes_box_xpath)
        for i in range (len(eles)):
            if eles[i].text in mediaType:
                eles[i].click()

    def getMediaTypeChooseStatus(self):
        """获取媒体类型选择状态"""
        statusList1 = []
        statusList2 = []
        statusList3 = []
        eles = self.dr.find_elements_by_xpath(ReadConfig().mediaTypes_checkbox_xpath)
        for ele in eles:
            statusList1.append([ele.text, ele.is_selected()])
            statusList2.append([ele.text, ele.is_enabled()])
            statusList3.append([ele.text, ele.is_displayed()])
        print(statusList1)
        print(statusList2)
        print(statusList3)

    def chooseMediaSource(self,mediaType=[]):
        """选择的数据来源，支持中文 以元组或列表形式传输"""
        if mediaType == "不选择":
            return self.dr.find_element_by_xpath(".//*[@id='reverse']").click()
        if mediaType == "点击全选":
            return self.dr.find_element_by_xpath(".//*[@id='selectAll1']").click()
        if len(mediaType)==0:
            return "并未传递需要取消选择的媒体类型"
        self.dr.find_element_by_xpath(".//*[@id='reverse']").click()
        eles = self.dr.find_elements_by_xpath(ReadConfig().mediaTypes_box_xpath)
        for i in range (len(eles)):
            if eles[i].text in mediaType:
                eles[i].click()

    def choosePropensity (self,propensity="1"):
        """倾向性选择 1 不限 2 正面 3 中性 4 负面"""
        eles=self.dr.find_elements_by_xpath(".//*[@id='main-content']/section/div/div/section[1]/div/form/div")
        i=0
        for ele in eles:
            i=i+1
            if "倾向性" in ele.text:
                self.dr.find_element_by_xpath(
                    ".//*[@id='main-content']/section/div/div/section[1]/div/form/div["+str(i)+"]/div/label["+propensity+"]/input"
                ).click()
                return None

    def setTimeRange(self, date='0'):
        """时间范围选择 0 当天 1 昨天 2 三天内 6 一周内
        100 自定义 自定义需输入起止时间的数组 %Y-%m-%d %H:%M:%S格式"""
        if date == "0":
            self.driver.click("id=>date0")
        elif date in ("1", "2", "6"):
            self.driver.click("id=>date-{}".format(date)).click()
        elif len(date) == 2:
                self.driver.click("id=>date100")
                self.driver.clear("=>starttime")
                self.driver.type("id=>starttime", date[0])
                self.driver.clear("id=>endtime")
                self.driver.type("id=endtime", date[1])
        else:
            print ("时间段选择有误，未做变更仍为默认时间 即当天\n时间范围选择 [0] 当天 [1] 昨天 [2] 三天内 [6] 一周内 或起止时间数组 ")

    def sumbit(self):
        """提交检索"""
        self.driver.click("id=>search")

    def setResultCount(self, value=None, button=None):
        """可选参数 Button=1000  5000  10000  50000  自动点击对应按钮
        value[高优先级]  可输入任意正整数  将会填写到手动输入框中"""
        if value:
            self.driver.clear("id=>max_count")
            self.driver.type("id=>max_count", value)
        elif button=="1000":
            self.driver.click("css=>.input-group-btn>button:nth-of-type(1)")
        elif button=="5000":
            self.driver.click("css=>.input-group-btn>button:nth-of-type(2)")
        elif button=="10000":
            self.driver.click("css=>.input-group-btn>button:nth-of-type(3)")
        elif button=="50000":
            self.driver.click("css=>.input-group-btn>button:nth-of-type(4)")
        else:
            print("未选择有效参数，系统未做变更")

    def keyWordsByAdvanced(self, logic="", ambiguousWords=""):
        """高级查询  ambiguousWords 歧义词"""
        self.driver.click("id=>query2")

        if logic != "":
            self.driver.type("id=>user_logic", logic)
        if ambiguousWords != "":
            self.driver.type("id=>amb_w_logic", ambiguousWords)

    def resultShowType(self,resType="excel"):
        """结果展现方式  在线编辑-->在线编辑  excel-->excel  sqlite-->sqlite json-->json
        网络地址 直接输入 网络地址即可 """
        resTypelower=resType.lower()
        if resTypelower == "在线编辑":
            self.driver.click("css=>input[value='online']")
        elif resTypelower == "excel":
            self.driver.click("css=>input[value='excel']")
        elif resTypelower == "sqlite":
            self.driver.click("css=>input[value='sqlite']")
        elif resTypelower == "json":
            self.driver.click("css=>input[value='json']")
        else:
            self.driver.click("css=>input[value='zmq']")
            time.sleep(0.5)
            if resTypelower != "不输入网络地址":
                self.driver.type("id=>zmqInput", resTypelower)

    def keyWordsByAccurate(self, w1=None, w2=None, w3=None):
        """精准查询 关键词设置"""
        self.driver.click("id=>query1")
        if w1:
            self.driver.type("id=>w1]", w1)
        if w2:
            self.driver.type("id=>w2", w2)
        if w3:
            self.driver.type("id=>w3", w3)

    # def webSiteChoose(self,website,*fullName):
    #     """站点选择 有问题  有可能点到全选"""
    #     self.dr.find_element_by_xpath(".//*[@id='webname']").send_keys(website)
    #     self.dr.find_element_by_xpath(".//*[@id='searchConfig']").click()
    #     for i in range(1,11):
    #         print(self.dr.find_element_by_xpath(".//*[@id='configID']/li["+str(i)+"]/a/label/span").text)
    #         if self.dr.find_element_by_xpath(".//*[@id='configID']/li["+str(i)+"]/a/label/span").text in fullName:
    #             print(True)
    #             self.dr.find_element_by_xpath(".//*[@id='configID']/li[" + str(i) + "]/a/label/input").click()

    #
    # def advancedSetting (self,domain=None,channel=None,source=None):
    #     """高级设置"""
    #     try:self.dr.find_element_by_xpath(".//*[@data-original-title='展开高级设置']/..").click()
    #     except:pass
    #     if domain != None:
    #         self.dr.find_element_by_xpath(".//*[@id='domain']").send_keys(domain)
    #     if channel != None:
    #         self.dr.find_element_by_xpath(".//*[@id='channel']").send_keys(channel)
    #     if source != None:
    #         self.dr.find_element_by_xpath(".//*[@id='source']").send_keys(source)
    #
    # def selectPluginsByName(self,name=None):
    #     """插件选择 目前默认仅选择第一个插件"""
    #     try:
    #         self.dr.find_element_by_xpath(".//*[@id='plugDiv']/../div[1]/button").click()
    #     except:
    #         self.dr.find_element_by_xpath(".//*[@data-original-title='展开高级设置']/..").click()
    #         time.sleep(2)
    #         self.dr.find_element_by_xpath(".//*[@id='plugDiv']/../div[1]/button").click()
    #     self.dr.switch_to.frame(self.dr.find_element_by_xpath(".//*[@src='/search/main.html?view=plug']"))
    #     self.dr.find_element_by_xpath(".//*[@id='plugUl']/li[1]/label").click()#选择第一个插件
    #
    #     self.dr.find_element_by_xpath("html/body/section/div/div[2]/button[1]").click()#点击确定
    #     self.dr.switch_to_default_content()
    #
    # def selectMarkerByName(self, *name):
    #     """标记选择"""
    #     try:
    #         self.dr.find_element_by_xpath(".//*[@id='markSet']/../div[1]/button").click()
    #     except:
    #         self.dr.find_element_by_xpath(".//*[@data-original-title='展开高级设置']/..").click()
    #         time.sleep(1)
    #         self.dr.find_element_by_xpath(".//*[@id='markSet']/../div[1]/button").click()
    #     self.dr.switch_to.frame(self.dr.find_element_by_xpath(".//*[@src='/search/main.html?view=markset']"))#跳转
    #     self.dr.find_element_by_xpath(".//*[@id='treeDemo_9_check']").click()
    #     self.dr.find_element_by_xpath("html/body/section/div/div[3]/button[1]").click()
    #     self.dr.switch_to_default_content()#跳回
    #
    # def selectAnalyzerByName(self,name=None):
    #     """分析器选择"""
    #     try:
    #         self.dr.find_element_by_xpath(".//*[@id='analyDiv']/../div[1]/button").click()
    #     except:
    #         self.dr.find_element_by_xpath(".//*[@data-original-title='展开高级设置']/..").click()
    #         time.sleep(2)
    #         self.dr.find_element_by_xpath(".//*[@id='analyDiv']/../div[1]/button").click()
    #     self.dr.switch_to.frame(self.dr.find_element_by_xpath(".//*[@src='/search/main.html?view=analy']"))
    #     if name == None:
    #         name = self.dr.find_element_by_xpath(".//*[@id='plugUl']/li[1]/label").text
    #         self.dr.find_element_by_xpath(".//*[@id='plugUl']/li[1]/label").click()  # 选择第一个分析器
    #         self.dr.find_element_by_xpath("html/body/section/div/div[2]/button[1]").click()  # 点击确定
    #         self.dr.switch_to_default_content()
    #         return name
    #     else:
    #         eles = self.dr.find_elements_by_xpath(".//*[@id='plugUl']/li/label")
    #         chooseAnalyzerList = []
    #         scrollTo=40
    #         for ele in eles:
    #             annlyzerName = ele.text
    #             # print(annlyzerName)
    #             if annlyzerName in name:
    #                 try:  #避免出现元素不可见
    #                     ele.click()
    #                 except:
    #                     pass
    #                 chooseAnalyzerList.append(annlyzerName)
    #                 name.remove(annlyzerName)
    #                 if len(name) == 0:break
    #             js = "window.scrollTo(0,{scrollTo})".format(scrollTo=scrollTo)
    #             scrollTo=scrollTo+40
    #             self.dr.execute_script(js)
    #         self.dr.find_element_by_xpath("html/body/section/div/div[2]/button[1]").click()  # 点击确定
    #         self.dr.switch_to_default_content()
    #         return chooseAnalyzerList
    #
    # # def chooseSourceInfo(self,*args):
    # #     try:
    # #         self.dr.find_element_by_xpath(".//*[@style='position: relative;']/div[5]/div/label[1]").click()
    # #     except:
    # #         self.dr.find_element_by_xpath(".//*[@data-original-title='展开高级设置']/..").click()
    # #         self.dr.find_element_by_link_text(".//*[@style='position: relative;']/div[5]/div/label[1]").click()
    # def addToFavorites(self,favoritesName=""):
    #     """添加到收藏夹  collectionName 收藏名称"""
    #     self.dr.find_element_by_xpath(".//*[@onclick='favorites();']").click()
    #     time.sleep(2)
    #     self.dr.switch_to_frame(self.dr.find_element_by_xpath(".//*[@src='/search/timer/main.html?view=favorites']"))
    #     if favoritesName != "编辑收藏夹" :
    #         self.dr.find_element_by_xpath(".//*[@id='name']").clear()
    #         self.dr.find_element_by_xpath(".//*[@id='name']").send_keys(favoritesName)
    #     self.dr.find_element_by_xpath(".//*[@id='submit']").click()
    #     self.dr.switch_to_default_content()

    # def getMsgTitle(self):
    #     """获取提示信息标题"""
    #     return self.dr.find_element_by_xpath(ReadConfig().MsgTitle_text_xpath).text
    # def getMsgContent(self):
    #     """获取提示信息内容"""
    #     return self.dr.find_element_by_xpath(ReadConfig().MsgContent_text_xpath).text
    # def clickOKButton(self):
    #     """点击提示框确定按钮"""
    #     return self.dr.find_element_by_xpath(ReadConfig().accept_button_xpath).click()
    # def fileHandle(self,returnFileName=None,downLoad=None):
    #     """处理检索的文件  是否返回文件名称  是否下载文件  下载仅支持Excel"""
    #     if not(returnFileName==downLoad==None):
    #         try:
    #             WebDriverWait(DataRetrieval().dr, 600).until(lambda driver: driver.find_element_by_xpath(".//*[@id='resultP']/p[3]/a"))
    #             time.sleep(5)
    #             filelink=DataRetrieval().dr.find_element_by_xpath(".//*[@id='resultP']/p[3]/a")
    #             filename = (filelink.text).split("/")[-1]
    #             if downLoad !=None:
    #                 filelink.click()
    #         except:
    #             pass
    #         if returnFileName != None:return filename
    #
    # def siteSearch_normal(self,w1=None,w2=None,w3=None,DomesticAndForeign=None,
    #                       resultShowType=None,times="0",chooseMediaType=None,
    #                     propensity="1",countlimit="100",domain=None,channel=None,source=None,plugins=None,
    #                     marker=None,analyzer=None,download=None,returnFileName=None,favoritesName=None):
    #     """DomesticAndForeign 境内外 1"全部   "2" 境内  "3"境外
    #     w1-->关键词1        w2-->关键词2           w3-->关键词3       resultType-->结果呈现类型     times-->时间
    #     cancelChooseMediaType-->取消选择的媒体类型  Propensity-->倾向性  countlimit-->结果条数限制
    #     domain-->域名         channel-->频道        source-->发帖人
    #     plugins-->插件        marker-->标记         analyzer-->分析器
    #     download-->下载文件 returnFileName-->返回文件名
    #
    #     """
    #     if DomesticAndForeign != None:
    #         self.chooseDomesticAndForeign(DomesticAndForeign)
    #     if chooseMediaType != None:
    #         self.chooseMediaType(chooseMediaType)
    #     if propensity !="1":
    #         self.choosePropensity(propensity)
    #     if times != "0":
    #         self.setTimeRange(times)
    #     if countlimit != "100":
    #         self.setResultCount(countlimit)
    #     if resultShowType != None:
    #         self.resultShowType(resultShowType)
    #     self.keyWordsByAccurate(w1,w2,w3)
    #     if not(domain==channel==source==None):
    #         self.advancedSetting(domain,channel,source)
    #     if plugins != None:self.selectPluginsByName(plugins) #插件待调试
    #     time.sleep(2)
    #     if marker != None:self.selectMarkerByName()
    #     time.sleep(2)
    #     if analyzer != None:self.selectAnalyzerByName(analyzer)
    #     time.sleep(2)
    #     if favoritesName != None:self.addToFavorites(favoritesName)
    #     else:
    #         self.dr.find_element_by_xpath(".//*[@id='search']").click()#提交
    #         return (self.fileHandle(returnFileName,download))
    #
    # def siteSearch_Logic(self, logic=None,ambiguousWords=None, resultShowType=None, time="0", cancelChooseMediaType=None,
    #                       Propensity="1", countlimit="100", domain=None, channel=None, source=None, plugins=None,
    #                       marker=None, analyzer=None, download=None, returnFileName=None):
    #     """logic-->逻辑表达式    ambiguousWords-->歧义词       resultType-->结果呈现类型     time-->时间
    #     cancelChooseMediaType-->取消选择的媒体类型  Propensity-->倾向性  countlimit-->结果条数限制
    #     domain-->域名         channel-->频道        source-->发帖人
    #     plugins-->插件        marker-->标记         analyzer-->分析器
    #     download-->下载文件 returnFileName-->返回文件名
    #
    #     """
    #     if cancelChooseMediaType != None:
    #         self.cancelChooseMediaType(cancelChooseMediaType)
    #     if Propensity != "1":
    #         self.choosePropensity(Propensity)
    #     if time != "0":
    #         self.setTimeRange(time)
    #     if countlimit != "100":
    #         self.setResultCount(countlimit)
    #     if resultShowType != None:
    #         self.resultShowType(resultShowType)
    #     self.keyWordsByAdvanced(logic,ambiguousWords)
    #     if not (domain == channel == source == None):
    #         self.advancedSetting(domain, channel, source)
    #     if plugins != None: self.selectPluginsByName(plugins)  # 插件待调试
    #     time.sleep(2)
    #     if marker != None: self.selectMarkerByName()
    #     time.sleep(2)
    #     if analyzer != None: self.selectAnalyzerByName()
    #     time.sleep(2)
    #     self.dr.find_element_by_xpath(".//*[@id='search']").click()  # 提交
    #     return (self.fileHandle(returnFileName, download))

if __name__=="__main__":
    pass